package com.gxd.redis.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;

/**
 * @Author:gxd
 * @Description:
 * @Date: 18:32 2018/1/8
 * @Modified By:
 */
@SuppressWarnings("SpringJavaAutowiringInspection") //加这个注解让IDE 不报: Could not autowire
@Configuration
@EnableCaching//启用缓存
public class CacheConfig extends CachingConfigurerSupport {
    private static final Logger logger = LoggerFactory.getLogger(CacheConfig.class);
    @Autowired(required = false)
    @Qualifier("gxdRedisProperties")
    private RedisProperties redisProperties;

    /**
     * 自定义key. 这个可以不用
     * 此方法将会根据类名+方法名+所有参数的值生成唯一的一个key,即使@Cacheable中的value属性一样，key也会不一样。
     */
    @Bean
    public KeyGenerator customKeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                //sb.append(target.getClass().getSimpleName());
                //sb.append(method.getName());
                for (Object o : params) {
                    sb.append(":").append(o.toString());
                }
                return redisProperties.getBizKey()+":"+method.getName()+sb.toString();
            }
        };
    }

    @PostConstruct
    private void initialize() {
        logger.debug("进入CacheConfig");
    }

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
       //设置缓存过期时间
       //rcm.setDefaultExpiration(redisClusterProperties.getExpireTime());//秒
        return rcm;
    }
}
